<template>
  <div class="task-list">
    <h1>任务列表</h1>
    <el-button type="primary" @click="goToCreate">创建任务</el-button>
    <el-table :data="groupedTasks" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="任务名称" />
      <el-table-column prop="type" label="任务类型" />
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="viewDetail(scope.row.id)">查看详情</el-button>
          <el-button 
            size="small" 
            type="success" 
            @click="startTask(scope.row.id)"
            :disabled="scope.row.status !== 'CREATED' && scope.row.status !== 'PAUSED'"
            v-if="!scope.row.isBatch || scope.row.isBatchMaster"
          >
            启动
          </el-button>
          <el-button 
            size="small" 
            type="warning" 
            @click="pauseTask(scope.row.id)"
            :disabled="scope.row.status !== 'RUNNING'"
            v-if="!scope.row.isBatch || scope.row.isBatchMaster"
          >
            暂停
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="deleteTask(scope.row.id)"
            :disabled="scope.row.status === 'RUNNING'"
            v-if="!scope.row.isBatch || scope.row.isBatchMaster"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      show-icon
      closable
      @close="clearError"
    />
    
    <el-alert
      v-if="successMessage"
      :title="successMessage"
      type="success"
      show-icon
      closable
      @close="clearSuccessMessage"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useTaskStore } from '@/stores/task'
import { ElMessageBox, ElMessage } from 'element-plus'

const router = useRouter()
const taskStore = useTaskStore()
const tasks = ref([])
const loading = ref(false)
const error = ref(null)
const successMessage = ref(null)

// 对任务进行分组，将批量任务合并显示
const groupedTasks = computed(() => {
  const groups: any = {}
  const result: any = []
  
  // 按任务名称前缀分组
  tasks.value.forEach((task: any) => {
    // 检查是否为批量任务（根据任务名称中是否包含"-"和箭头符号判断）
    const isBatch = task.name.includes(' - ') && task.name.includes(' → ')
    
    if (isBatch) {
      // 提取批量任务的主名称（箭头前的部分）
      const masterName = task.name.split(' - ')[0]
      
      if (!groups[masterName]) {
        groups[masterName] = {
          ...task,
          name: masterName,
          isBatch: true,
          isBatchMaster: true,
          subTasks: [task]
        }
      } else {
        groups[masterName].subTasks.push(task)
        
        // 更新主任务状态为所有子任务中最差的状态
        const statusPriority = ['FAILED', 'RUNNING', 'PAUSED', 'CREATED', 'COMPLETED']
        const currentPriority = statusPriority.indexOf(groups[masterName].status)
        const newPriority = statusPriority.indexOf(task.status)
        if (newPriority < currentPriority) {
          groups[masterName].status = task.status
        }
      }
    } else {
      // 非批量任务直接添加
      result.push({
        ...task,
        isBatch: false
      })
    }
  })
  
  // 将分组后的批量任务添加到结果中
  Object.values(groups).forEach((group: any) => {
    result.push(group)
  })
  
  // 添加未分组的子任务
  tasks.value.forEach((task: any) => {
    const isBatch = task.name.includes(' - ') && task.name.includes(' → ')
    const isAlreadyAdded = result.some((item: any) => 
      item.isBatch && item.subTasks.some((subTask: any) => subTask.id === task.id) ||
      !item.isBatch && item.id === task.id
    )
    
    if (isBatch && !isAlreadyAdded) {
      result.push({
        ...task,
        isBatch: true,
        isBatchMaster: false
      })
    }
  })
  
  return result
})

// 跳转到创建任务页面
const goToCreate = () => {
  router.push('/tasks/create')
}

// 查看任务详情
const viewDetail = (taskId: string) => {
  router.push(`/tasks/${taskId}`)
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'RUNNING':
      return 'primary'
    case 'COMPLETED':
      return 'success'
    case 'FAILED':
      return 'danger'
    case 'PAUSED':
      return 'warning'
    default:
      return 'info'
  }
}

// 启动任务
const startTask = async (taskId: string) => {
  try {
    // 查找对应的任务对象
    const task = groupedTasks.value.find((t: any) => t.id == taskId)
    
    if (task && task.isBatch && task.isBatchMaster) {
      // 如果是批量任务主任务，需要启动所有子任务
      let successCount = 0
      let failCount = 0
      
      for (const subTask of task.subTasks) {
        try {
          await taskStore.startTask(subTask.id)
          successCount++
        } catch (err) {
          failCount++
        }
      }
      
      if (failCount === 0) {
        successMessage.value = `批量任务启动成功，共启动${successCount}个子任务`
      } else {
        successMessage.value = `批量任务启动完成，成功${successCount}个，失败${failCount}个`
      }
    } else {
      // 单个任务直接启动
      const result = await taskStore.startTask(taskId)
      successMessage.value = result.message
    }
    
    // 刷新任务列表
    await loadTasks()
  } catch (err: any) {
    error.value = err.message || '启动任务失败'
  }
}

// 暂停任务
const pauseTask = async (taskId: string) => {
  try {
    // 查找对应的任务对象
    const task = groupedTasks.value.find((t: any) => t.id == taskId)
    
    if (task && task.isBatch && task.isBatchMaster) {
      // 如果是批量任务主任务，需要暂停所有子任务
      let successCount = 0
      let failCount = 0
      
      for (const subTask of task.subTasks) {
        try {
          await taskStore.pauseTask(subTask.id)
          successCount++
        } catch (err) {
          failCount++
        }
      }
      
      if (failCount === 0) {
        successMessage.value = `批量任务暂停成功，共暂停${successCount}个子任务`
      } else {
        successMessage.value = `批量任务暂停完成，成功${successCount}个，失败${failCount}个`
      }
    } else {
      // 单个任务直接暂停
      const result = await taskStore.pauseTask(taskId)
      successMessage.value = result.message
    }
    
    // 刷新任务列表
    await loadTasks()
  } catch (err: any) {
    error.value = err.message || '暂停任务失败'
  }
}

// 删除任务
const deleteTask = async (taskId: string) => {
  try {
    // 查找对应的任务对象
    const task = groupedTasks.value.find((t: any) => t.id == taskId)
    
    if (task && task.isBatch && task.isBatchMaster) {
      // 如果是批量任务主任务，需要确认是否删除所有子任务
      await ElMessageBox.confirm(
        `确认删除该批量任务及其包含的${task.subTasks.length}个子任务吗？此操作不可恢复。`,
        '警告',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      
      let successCount = 0
      let failCount = 0
      
      for (const subTask of task.subTasks) {
        try {
          await taskStore.deleteTask(subTask.id)
          successCount++
        } catch (err) {
          failCount++
        }
      }
      
      if (failCount === 0) {
        successMessage.value = `批量任务删除成功，共删除${successCount}个子任务`
      } else {
        successMessage.value = `批量任务删除完成，成功${successCount}个，失败${failCount}个`
      }
    } else {
      // 单个任务直接删除
      await ElMessageBox.confirm(
        '确认删除该任务吗？此操作不可恢复。',
        '警告',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      
      await taskStore.deleteTask(taskId)
      successMessage.value = '任务删除成功'
    }
    
    // 刷新任务列表
    await loadTasks()
  } catch (err: any) {
    if (err !== 'cancel') {
      error.value = err.message || '删除任务失败'
    }
  }
}

// 清除错误信息
const clearError = () => {
  error.value = null
}

// 清除成功信息
const clearSuccessMessage = () => {
  successMessage.value = null
}

// 加载任务列表
const loadTasks = async () => {
  loading.value = true
  try {
    await taskStore.fetchTasks()
    tasks.value = taskStore.tasks
  } catch (err) {
    error.value = '获取任务列表失败'
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载任务列表
onMounted(() => {
  loadTasks()
})
</script>

<style scoped>
.task-list {
  padding: 20px;
}
</style>